package com.gears_software.sxdc.dccx.ui.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.ICPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.RequestUrl;
import com.gears_software.sxdc.dccx.data.model.CPOrderDetailModel;
import com.gears_software.sxdc.dccx.data.model.PositionEntity;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RDriverArrivedModel;
import com.gears_software.sxdc.dccx.ui.activity.ComplainActivity_;
import com.gears_software.sxdc.dccx.ui.activity.HaveCompletedActivity_;
import com.gears_software.sxdc.dccx.ui.activity.MainActivity;
import com.gears_software.sxdc.dccx.ui.activity.TripInformationActivity;
import com.gears_software.sxdc.dccx.ui.event.UpdateTripListEvent;
import com.gears_software.sxdc.dccx.ui.map.LocationTask;
import com.gears_software.sxdc.dccx.ui.map.OnLocationGetListener;
import com.gears_software.sxdc.dccx.ui.map.RegeocodeTask;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by SunMuran on 2017/7/29.
 */
@EViewGroup(R.layout.item_trip_information_new)
public class TripInformationNewItemView extends LinearLayout implements OnLocationGetListener {
    Context context;
    @App
    DCCXApplication app;
    @ViewById
    TextView tv_phone_number;
    @ViewById
    TextView tv_go_off;
    @ViewById
    TextView tv_reserve_seat;
    @ViewById
    TextView tv_entruching_point;
    @ViewById
    TextView tv_remarks;
    @ViewById
    RelativeLayout re_header;
    @ViewById
    TextView txt_time;
    @ViewById
    TextView txt_didian;
    @ViewById
    TextView txt_remark;
    @ViewById
    TextView txt_confrimyd;
    @ViewById
    RelativeLayout re_yuding;
    @ViewById
    TextView txt_ding;
    @ViewById
    TextView txt_evaluate;
    @ViewById
    TextView txt_pay_state;
    @ViewById
    RelativeLayout re_evaluate;
    @ViewById
    RelativeLayout re_tel;
    @ViewById
    RelativeLayout re_complaint;
    @ViewById
    RelativeLayout re_chezhu_button;
    @RestService
    ICPOrderFinder orderFinder;
    @ViewById
    SimpleDraweeView img_passenger_avatar;
    @Bean
    OttoBus bus;
    CPOrderDetailModel detailModel;
    int seat;
    //地图部分自己封装的定位包
    private LocationTask mLocationTask;
    private RegeocodeTask mRegeocodeTask;
    String address;
    double latitue;
    double longitude;


    public TripInformationNewItemView(Context context) {
        super(context);
        this.context = context;
    }

    public void bind(CPOrderDetailModel cpOrderDetailModel) {
        this.detailModel = cpOrderDetailModel;
        txt_time.setTypeface(app.iconfont);
        txt_didian.setTypeface(app.iconfont);
        txt_remark.setTypeface(app.iconfont);
        txt_ding.setTypeface(app.iconfont);

        tv_phone_number.setText(cpOrderDetailModel.getPassengerphone());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        tv_go_off.setText(sf.format(cpOrderDetailModel.getrTime()));
        tv_reserve_seat.setText(String.valueOf(cpOrderDetailModel.getPassengernum()));
        seat = cpOrderDetailModel.getPassengernum();
        tv_entruching_point.setText(cpOrderDetailModel.getDeparture());
        if (cpOrderDetailModel.getPassengeravatar() != null && !cpOrderDetailModel.getPassengeravatar().equals("")) {
            Uri avatarUrl = Uri.parse(cpOrderDetailModel.getPassengeravatar() + RequestUrl.avatar);
            img_passenger_avatar.setImageURI(avatarUrl);
        }

        //判断是否有备注
        if (cpOrderDetailModel.getMemo() == null || cpOrderDetailModel.getMemo().equals("")) {
            tv_remarks.setText("无");
        } else {
            tv_remarks.setText(cpOrderDetailModel.getMemo());
        }
        //判断司机是否确认预定
        if (cpOrderDetailModel.getDriveraccpet() != null) {
            txt_confrimyd.setText("已到达");
            re_yuding.setEnabled(true);
            txt_ding.setVisibility(VISIBLE);
            re_complaint.setVisibility(VISIBLE);
            //判断是否显示评价按钮
            if (!cpOrderDetailModel.getIspay().equals("1")) {
                re_evaluate.setVisibility(GONE);
                txt_pay_state.setVisibility(GONE);

            } else {
                txt_pay_state.setVisibility(VISIBLE);
                re_evaluate.setVisibility(VISIBLE);
                if (cpOrderDetailModel.getDrivereva() != null && cpOrderDetailModel.getDrivereva().equals("1")) {
                    re_evaluate.setEnabled(false);
                    txt_evaluate.setTextColor(ContextCompat.getColor(context, R.color.colorFontBigGray));
                    txt_evaluate.setText("已评价");
                } else {
                    re_evaluate.setEnabled(true);
                }
            }
            //判断是否到达上车地点
            if (cpOrderDetailModel.getIsarrive() != null && cpOrderDetailModel.getIsarrive().equals("1")) {
                re_yuding.setEnabled(false);
                txt_confrimyd.setTextColor(ContextCompat.getColor(context, R.color.colorFontBigGray));
            }
        } else {
            txt_ding.setVisibility(GONE);
            re_yuding.setEnabled(true);
            txt_confrimyd.setText("确认预定");
            re_complaint.setVisibility(GONE);
            re_evaluate.setVisibility(GONE);
        }

        if (cpOrderDetailModel.getCancelparty() != null && (cpOrderDetailModel.getCancelparty().equals("1") || cpOrderDetailModel.getCancelparty().equals("3"))) {
            txt_ding.setVisibility(VISIBLE);
            txt_ding.setText(R.string.carowner_trip_item_cancel_icon);
            txt_ding.setTextColor(ContextCompat.getColor(context, R.color.colorFontOrange));
            re_chezhu_button.setVisibility(GONE);
        } else if (cpOrderDetailModel.getCancelparty().equals("2") && cpOrderDetailModel.getAcceptcancel() != null) {
            txt_ding.setVisibility(VISIBLE);
            txt_ding.setText(R.string.carowner_trip_item_cancel_icon);
            txt_ding.setTextColor(ContextCompat.getColor(context, R.color.colorFontOrange));
            re_chezhu_button.setVisibility(GONE);
        } else {
            re_chezhu_button.setVisibility(VISIBLE);
        }
    }

    @Click
    void re_tel() {

        new MaterialDialog.Builder(context)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontBigGray)
                .content("您确定要拨打" + " " + detailModel.getPassengerphone())
                .contentColorRes(R.color.colorFontBigGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(context, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        AndPermission.with(context)
                                .requestCode(100)
                                .permission(Manifest.permission.CALL_PHONE)
                                .callback(listener)
                                .rationale(new RationaleListener() {
                                    @Override
                                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                        AndPermission.rationaleDialog(context, rationale).
                                                show();
                                    }
                                })
                                .start();
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(context, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();

    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                //打电话
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + detailModel.getPassengerphone()));
                context.startActivity(intent);
            } else if (requestCode == 200) {
                mLocationTask.startSingleLocate();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 100) {
                TastyToast.makeText(context, "获取电话权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            } else if (requestCode == 200) {
                TastyToast.makeText(context, "获取定位权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            }
        }
    };

    @Click
    void re_yuding() {
        if (detailModel.getDriveraccpet() != null) {
            mLocationTask = new LocationTask(context);
            mLocationTask.setOnLocationGetListener(this);
            mRegeocodeTask = new RegeocodeTask(context);

            //获取定位权限
            AndPermission.with(context)
                    .requestCode(200)
                    .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                    .callback(listener)
                    .rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(context, rationale).
                                    show();
                        }
                    })
                    .start();
        } else {
            goAccept();
        }
    }

    @Background
    void goAccept() {
        Logger.d(detailModel.getId());
        ResultModel<String> res = orderFinder.goAccept(detailModel.getId());
        showAcceptResult(res);
    }

    @UiThread
    void showAcceptResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(context, "确认预定成功", app.SHORT, app.SUCCESS);
                txt_confrimyd.setText("已预定");
                re_yuding.setEnabled(false);
                txt_ding.setVisibility(VISIBLE);
                bus.post(new UpdateTripListEvent(((TripInformationActivity) context).id, seat));

            } else {
                TastyToast.makeText(context, res.getErrmsg(), app.LONG, app.ERROR);
            }
        }
    }

    @Background
    void driverArrived(RDriverArrivedModel arrivedModel) {
        ResultModel<String> res = orderFinder.driverArrived(arrivedModel);
        showArrivedResult(res);
    }

    @UiThread
    void showArrivedResult(ResultModel<String> res) {
        mLocationTask.onDestroy();
        if (res != null) {
            if (res.getErrno().equals("0")) {
                re_yuding.setEnabled(false);
                txt_confrimyd.setTextColor(ContextCompat.getColor(context, R.color.colorFontBigGray));
                TastyToast.makeText(context, "车主地理位置信息提交成功", app.SHORT, app.SUCCESS);
            } else {
                TastyToast.makeText(context, res.getErrmsg(), app.LONG, app.ERROR);
            }
        }
    }

    @Click
    void re_complaint() {
        Intent intent = new Intent(context, ComplainActivity_.class);
        intent.putExtra("flag", "1");
        intent.putExtra("id", detailModel.getId());
        intent.putExtra("orderDetailModel", detailModel);
        context.startActivity(intent);
    }

    @Override
    public void onLocationGet(PositionEntity entity, AMapLocation aMapLocation) {
        address = entity.getAddress();
        latitue = entity.getLatitue();
        longitude = entity.getLongitude();
        RDriverArrivedModel arrivedModel = new RDriverArrivedModel();
        arrivedModel.setOrderid(((TripInformationActivity) context).id);
        arrivedModel.setId(detailModel.getId());
        arrivedModel.setArrivelatitude(String.valueOf(latitue));
        arrivedModel.setArrivelongitude(String.valueOf(longitude));
        arrivedModel.setArriveplace(String.valueOf(address));
        driverArrived(arrivedModel);

    }

    @Click
    void re_evaluate() {
        Intent intent = new Intent(context, HaveCompletedActivity_.class);
        intent.putExtra("flag", "1");
        intent.putExtra("id", detailModel.getId());
        intent.putExtra("orderDetailModel", detailModel);
        ((TripInformationActivity) context).startActivityForResult(intent, 1);
    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {
        Logger.d("走了吗");
    }


}
